﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Configuration;
using BOMS.Lib.Net;
using BOMSConsoleService.Lib;
using BOMS.Lib;
using BOMS.DATA;
using BOMS.Utility.DATA;
using BOMS.ConsoleService.DATA;
using System.Text.RegularExpressions;

namespace BOMS.ConsoleService
{
    public class SrvMngr
    {
        //创建TCP服务器类的对象
        //svr = new TcpSvr(8000, 4, new Coder(Coder.EncodingMothord.UTF8));
        TcpSvr svr = new TcpSvr(100);//100：表示最大允许100个客户端连接；使用默认编码方式 
        Log lg = new Log();
        Boolean IsOnlyPrintDataShort = bool.Parse(ConfigurationManager.AppSettings["LogExceptionFlag"]);
        public SrvMngr()
        {
            Output.PrintLine("进入BOMS服务");
        }
        public void Start()
        {
           // svr.Resovlver = new DatagramResolver("##");

            //注册服务器的4个事件

            //服务器满 
            svr.ServerFull += new NetEvent(this.ServerFull);

            //新客户端连接 
            svr.ClientConn += new NetEvent(this.ClientConn);

            //客户端关闭 
            svr.ClientClose += new NetEvent(this.ClientClose);

            //接收到数据 
            svr.RecvData += new NetEvent(this.RecvData);
           
            try
            {
                Output.Print("准备开启服务端口... ");
                ushort localPort = ushort.Parse(ConfigurationManager.AppSettings["ConsoleServiceTCPPort"]);
                svr.Start(localPort);
                Output.PrintLine("开启成功！");
                //打印消息显示当前侦听的端口号                
                //Console.WriteLine("当前正在侦听的端口号为：" + svr.ServerSocket.LocalEndPoint.ToString());
                Output.PrintLine("当前正在侦听的端口号为：" + svr.ServerSocket.LocalEndPoint.ToString());
                //SetTextControl("服务器已经开启", 0, true, this.labelState);
                //Console.Read();
               // Console.ReadKey(true);
            }
            catch(Exception ex)
            {
                Output.PrintLine(MsgType.Error,ex.Message);
                lg.log(ex);
            }
        }
        ///-----------------------------------------------------------------*
        /// <summary>
        /// 客户端容量达到上限 时的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///-----------------------------------------------------------------*
        void ServerFull(object sender, NetEventArgs e)
        {
            string info = string.Format
                ("Server is full.the Client:{0} is refused",
            e.Client.ClientSocket.RemoteEndPoint.ToString());

            //Must do it 
            //服务器满了,必须关闭新来的客户端连接 
            e.Client.Close();
            Output.PrintLine(MsgType.Warning, info);
           // SetTextControl(info, 1, true, this.textBoxFeedBack);

        }
        ///-----------------------------------------------------------------*
        /// <summary>
        /// 客户端连接服务器成功时发生的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///-----------------------------------------------------------------*
        void ClientConn(object sender, NetEventArgs e)
        {
            string info = string.Format
                ("A Client:{0} connect server Session:{1}. Socket Handle:{2}",
                e.Client.ClientSocket.RemoteEndPoint.ToString(),
            e.Client.ID, e.Client.ClientSocket.Handle);
            //e.Client.ByteArrayList.
            Output.PrintLine(info);
           // SetTextControl(info, 1, true, this.textBoxFeedBack);
        }
        ///-----------------------------------------------------------------*
        /// <summary>
        /// 客户端关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///-----------------------------------------------------------------*
        void ClientClose(object sender, NetEventArgs e)
        {
            string info;

            if (e.Client != null)
            {
                //Session.ExitType tempOne = e.Client.TypeOfExit;
                //SessionId tempTwo = e.Client.ID;
                if (e.Client.TypeOfExit == Session.ExitType.ExceptionExit)
                {
                    info = string.Format
                        ("A Client Session:{0} Exception Closed.", e.Client.ID);
                }
                else
                {
                    info = string.Format
                    
                        ("A Client Session:{0} Normal Closed.", e.Client.ID);
                }
                Output.PrintLine(info);
                //SetTextControl(info, 1, true, this.textBoxFeedBack);
            }
            /** */
        }
        ///-----------------------------------------------------------------*
        /// <summary>
        /// 收到数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///-----------------------------------------------------------------*
        void RecvData(object sender, NetEventArgs e)
        {
            try
            {
                //string rcvData = e.Client.Datagram;
                List<ByteArrayInfo> arr = e.Client.ByteArrayList;
                if (arr == null || arr.Count == 0) return;
                ProtocolPack pack = BuildData.Converting(arr[0].HexArray);
                //去掉"##"结束标志
                // string dataToShow = rcvData.Substring(0, rcvData.Length - 2);
                string info = string.Format
                    ("recv data from {0} =>", e.Client);
                Output.Print(info);
                info = string.Format("{0}",byteToHexStr(arr[0].HexArray, IsOnlyPrintDataShort));
                Output.Print(info);
                info = string.Format("({0})", DateTime.Now.ToString("HH:mm:ss"));
                Output.PrintLine(info);

                string xml = BuildData.OutputXML(pack);
                string ip = e.Client.ClientSocket.RemoteEndPoint.ToString();
                ip = Regex.Replace(ip, ":\\d+", "");
                string mac = "00-22-11-2B-4D-F7";//预置mac
                DateTime dtm = DateTime.Now;
                if (mac != "" && mac != "00-00-00-00-00-00")
                {
                    // DataUti.ImportEquipData(ip, mac, dtm, xml);
                    //DataUti2.ImportEquipData(ip, mac, dtm, xml);
                    DataUti2.ImportEquipData(ip, ip, dtm, xml);
                }
            }
            catch (Exception ex)
            {
                Output.PrintLine(MsgType.Error, ex.Message);
                lg.log(ex);
            }

        }
        public static string byteToHexStr(byte[] bytes,bool IsShorted)
        {
            StringBuilder returnStr = new StringBuilder();
            if (!IsShorted)
            {
                if (bytes != null)
                {
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        returnStr.AppendFormat(bytes[i].ToString("X2") + " ");
                    }
                }
            }
            else
            {
                if (bytes.Length > 10)
                {
                    int i;
                    for (i = 0; i < 10; i++)
                    {
                        returnStr.AppendFormat(bytes[i].ToString("X2") + " ");
                    }
                    returnStr.Append("……");
                    for (i = bytes.Length-10; i < bytes.Length; i++)
                    {
                        returnStr.AppendFormat(bytes[i].ToString("X2") + " ");
                    }
                }
            }
            return returnStr.ToString();
        }


    }
}
